//
//  viewer.cpp
//  xed_vfx_engine
//
//  Created by 岳伸 富田 on 11/11/09.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//
#include <iostream>

#include "Viewer.h"
#include "viewershader.h"

namespace Graphic {

/**
 * Class Viewer::Impl
 * Desc:
 */
class Viewer::Impl
{
public:
  struct Grid {
	float size;
	float color[3];
	int count;
	bool visible;
	
	Grid(){
	  size=1.0f;
	  color[0]=color[1]=color[2]=1.0f;
	  count=10;
	  visible=true;
	}
  };
  
  struct Axis {
	float size;
	bool visible;
	
	Axis(){
	  size=1.0f;
	  visible=true;
	}
  };
  
  Core* pCore;
  Grid grid;
  Axis axis;
  ViewerShader shader;
  
  void DrawGridAndAxis();
  
}; // class Viewer::Impl

/**
 * Name: DrawGridAndAxis
 * Desc:
 */
static void drawLine(const VMA::Vector3& p0, const VMA::Vector3& p1)
{
  float poses[6];
  poses[0]=p0[0];
  poses[1]=p0[1];
  poses[2]=p0[2];
  poses[3]=p1[0];
  poses[4]=p1[1];
  poses[5]=p1[2];
  
  glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,poses);
  glDrawArrays(GL_LINES,0,2);
}

void Viewer::Impl::DrawGridAndAxis()
{
#if 1
  shader.Bind(0);
  shader.SetWVP(pCore->GetProjMatrix()*pCore->GetViewMatrix());
  
  shader.SetUniform4f(UniformLocColor,VMA::Vector4(grid.color[0],grid.color[1],grid.color[2],1.0f));
  glDisable(GL_TEXTURE_2D);
  
  glEnableVertexAttribArray(0);
  
  /* draw grid */
  for(int i=-grid.count;i<grid.count+1;i++){
	drawLine(VMA::Vector3((float)(-grid.size*grid.count),0,(float)(i*grid.size)),
			 VMA::Vector3((float)( grid.size*grid.count),0,(float)(i*grid.size)));
	
	drawLine(VMA::Vector3((float)(i*grid.size),0,(float)(-grid.size*grid.count)),
			 VMA::Vector3((float)(i*grid.size),0,(float)( grid.size*grid.count)));
  }
  
  /* draw axis */
  shader.SetUniform4f(UniformLocColor,VMA::Vector4(1.0f,0,0,1.0f));
  drawLine(VMA::Vector3(0,0,0),VMA::Vector3(axis.size,0,0));
  
  shader.SetUniform4f(UniformLocColor,VMA::Vector4(0,1.0f,0,1.0f));
  drawLine(VMA::Vector3(0,0,0),VMA::Vector3(0,axis.size,0));
  
  shader.SetUniform4f(UniformLocColor,VMA::Vector4(0,0,1.0f,1.0f));
  drawLine(VMA::Vector3(0,0,0),VMA::Vector3(0,0,axis.size));
  
  shader.Unbind();
#else
  printf("hoge\n");
#endif
}


/**
 * Class Viewer
 * Desc:
 */

/**
 * Name: Viewer
 * Desc:
 */
 Viewer::Viewer() 
   : m_pImpl(NULL)
 {
	//
 }

/**
 * Name: ~Viewer
 * Desc:
 */
 Viewer::~Viewer() 
 {
	//
 }


/**
 * Name: Init
 * Desc:
 */
void Viewer::Init()
{
  if(m_pImpl!=NULL){
	return ;
  }
  
  Core::Init();
  m_pImpl=new Impl();
  m_pImpl->pCore=this;
  m_pImpl->shader.Init();
}


/**
 * Name: Destroy
 * Desc:
 */
void Viewer::Destroy()
{
  if(m_pImpl!=NULL){
	m_pImpl->shader.Destroy();
	delete m_pImpl;
	m_pImpl=NULL;
  }
  
  Core::Destroy();
}

/**
 * Name: Updata
 * Desc:
 */
void Viewer::Update(float elapsedTime)
{
  Core::Update(elapsedTime);
}

/**
 * Name: Render
 * Desc:
 */
void Viewer::Render(unsigned int frame)
{
  if(m_pImpl==NULL){
	return ;
  }
  
  Core::Render(frame);
  m_pImpl->DrawGridAndAxis();
}
} // namespace Graphic
